package com.teleca.jamendo.dialog;

import java.util.ArrayList;

import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;

import com.teleca.jamendo.JamendoApplication;
import com.teleca.jamendo.api.JamendoGet2Api;
import com.teleca.jamendo.api.WSError;
import com.teleca.jamendo.api.impl.JamendoGet2ApiImpl;
import com.teleca.jamendo.mode.Album;
import com.teleca.jamendo.mode.Review;
import com.teleca.jamendo.mode.Track;
import com.teleca.jamendo.ui.activity.AlbumActivity;

public class AlbumLoadingDialog extends LoadingDialog<Object, Integer> {

	Review[] mReviews;
	Album mAlbum;
	int mSelectedReviewId = -1;

	public AlbumLoadingDialog(Activity activity, int loadingMsg, int failMsg) {
		super(activity, loadingMsg, failMsg);
	}

	@Override
	public Integer doInBackground(Object... params) {
		mAlbum = (Album) params[0];
		if (params.length > 1) {
			mSelectedReviewId = (Integer) params[1];
		}
		try {
			loadReviews(mAlbum);
			loadTracks(mAlbum);
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		} catch (WSError e) {
			publishProgress(e);
			this.cancel(true);
		}
		return 1;
	}

	@Override
	public void doStuffWithResult(Integer result) {

		ArrayList<Review> reviews = new ArrayList<Review>();

		for (Review review : mReviews)
			reviews.add(review);

		Intent intent = new Intent(mActivity, AlbumActivity.class);
		intent.putExtra("album", mAlbum);
		intent.putExtra("reviews", reviews);
		intent.putExtra("selectedReviewId", mSelectedReviewId);
		mActivity.startActivity(intent);

	}

	private void loadReviews(Album album) throws JSONException, WSError {
		JamendoGet2Api server = new JamendoGet2ApiImpl();
		mReviews = server.getAlbumReviews(album);
	}

	private void loadTracks(Album album) throws JSONException, WSError {
		JamendoGet2Api service = new JamendoGet2ApiImpl();
		Track[] tracks = service.getAlbumTracks(album, JamendoApplication.getInstance().getStreamEncoding());
		album.setTracks(tracks);
	}
}
